package org.advanced.reflection;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author John.zhang
 * @version Id: BallTest, v 1.0 2020/12/3 19:38 ZhiYong Exp $
 */
public class BallTest {

    public static void main(String[] args) throws Exception {
        String key = "User";
        long start = System.currentTimeMillis();
        int max = 10000;
        for (int i = 0; i < max; i++) {
            getInstanceReflectByKey(key);
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }


    public static IUser getInstanceReflectByKey(String key) throws Exception {
        String basePackage = "org.advanced.reflection";
        Class<?> aClass = Class.forName(basePackage + "." + key);
        return (IUser) aClass.newInstance();
    }

    /**
     * 反射获取类对象
     *
     * @throws Exception
     */
    public static void reflectClazz() throws Exception {
        Class<User> userClass = User.class;
        Class<?> aClass = Class.forName("org.advanced.reflection.User");
        Class<? extends User> aClass1 = new User().getClass();
        Class<?> aClass2 = BallTest.class.getClassLoader().loadClass("org.advanced.reflection.User");


        //基本操作
        aClass1.getModifiers();//修饰符
        aClass1.getPackage();
        //...
        aClass1.getSimpleName();
        aClass1.getInterfaces();//获取类型所有的实现接口
        aClass1.getAnnotations();
    }


    public static void reflectUser() throws Exception {
        Class<User> userClass = User.class;
        User user = userClass.newInstance();

        //当前类以及父类公用字段
        Field[] fields = userClass.getFields();
        //可以获取私有的  只能获取当前类中的
        Field[] declaredFields = userClass.getDeclaredFields();

        for (Field field : fields) {
            System.out.println(field.getModifiers() + "-" + field.getName());
        }

        Field nameField = userClass.getDeclaredField("name");
        //修改私有属性的信息
        nameField.setAccessible(true);
        nameField.set(user, "John");
        System.out.println(user.getName());

        //静态属性赋值
        Field addressField = userClass.getDeclaredField("address");
        addressField.set(null, "江苏");


        //可以获取当前类以及父类中所有的公用方法
        Method[] methods = userClass.getMethods();
        //获取本类中所有的方法，包括私有的
        Method[] declaredMethods = userClass.getDeclaredMethods();


        Method method = userClass.getMethod("getUser");
        Method declaredMethod = userClass.getDeclaredMethod("updateUser");
        declaredMethod.setAccessible(true);
        declaredMethod.invoke(user);

        Method addUser = userClass.getDeclaredMethod("addUser", String.class);
        addUser.invoke(null, "");
    }


}
